package com.daykw.xiaohongshu.task.thread;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.codehaus.plexus.util.StringUtils;
import org.json.JSONObject;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.impl.NutDao;

import com.daykw.xiaohongshu.http.HttpBase;
import com.daykw.xiaohongshu.model.TAuthorNextTask;
import com.daykw.xiaohongshu.model.TKeywordNextTask;
import com.daykw.xiaohongshu.model.TKeywordTask;
import com.daykw.xiaohongshu.util.SpringContextHolder;

public class KeywordJobThread implements Runnable {

	private static Logger logger = Logger.getLogger(KeywordJobThread.class);
	private TKeywordTask task;
	private String ip;
	private Integer port;

	public KeywordJobThread(TKeywordTask task){
		this.task = task;
	}
	
	public KeywordJobThread(TKeywordTask task,String ip) {
		this.task = task;
		this.ip = ip.split(":")[0];
		this.port = Integer.valueOf(ip.split(":")[1]);
	}

	@Override
	public void run() {
		NutDao dao = SpringContextHolder.getBean("dao");
		try {
			dao.update(TKeywordTask.class, Chain.make("status", 1), Cnd.where("id", "=", task.getId()));
			String k = java.net.URLEncoder.encode(task.getKeyword(), "utf-8");
			String url = "http://www.xiaohongshu.com/web_api/sns/v2/search/trending?keyword=" + k;
			HttpBase http = new HttpBase();
			Map<String, String> headers = new HashMap<String, String>();
			headers.put("Accept", "application/json, text/plain, */*");
			headers.put("Accept-Encoding", "gzip, deflate, sdch");
			headers.put("Accept-Language", "zh-CN,zh;q=0.8");
			headers.put("Cache-Control", "max-age=0");
			headers.put("Cookie",
					"xhsTrackerId=9ed6751b-39ee-4682-c610-b1f96d102595; exp_ids=m_TestA-ctl2; Hm_lvt_d0ae755ac51e3c5ff9b1596b0c09c826=1515084426; Hm_lpvt_d0ae755ac51e3c5ff9b1596b0c09c826=1515084426; Hm_lvt_9df7d19786b04345ae62033bd17f6278=1515084426; Hm_lpvt_9df7d19786b04345ae62033bd17f6278=1515084430; xhs_spid.5dde=5fc5a7b7c9148948.1515084421.1.1515084433.1515084421.951e5781-af93-46c0-8994-797318048a51; xhs_spses.5dde=*");
			headers.put("Host", "www.xiaohongshu.com");
			headers.put("Referer", "http://www.xiaohongshu.com/");
			headers.put("Upgrade-Insecure-Requests", "1");
			headers.put("User-Agent",
					"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36");
			//String html = http.request(url, "utf-8", headers,ip,port).getResult();
			String html = http.get(url, "utf-8", headers,true);
			while ((StringUtils.isEmpty(html) || html.equals("fail")) ||(StringUtils.isNotEmpty(html) && html.indexOf("403 Forbidden") >= 0)) {
				//html = http.turl(url, "utf-8", headers,true);
				html = http.get(url, "utf-8", headers,true);
				//logger.error("################警告403 Forbidden IP封锁############");
				//dao.update(TKeywordTask.class, Chain.make("status", 3), Cnd.where("id", "=", task.getId()));
				//return;
			}
			if(html.equals("404")){
				dao.update(TKeywordTask.class, Chain.make("status", 3), Cnd.where("id", "=", task.getId()));
				return;
			}
			
			JSONObject json = new JSONObject(html);
			if(!json.getJSONObject("data").has("notes_hits")){
				dao.update(TKeywordTask.class, Chain.make("status", 0), Cnd.where("id", "=", task.getId()));
				return;
			}
			String notes_hits = "";
			try{
				 notes_hits = json.getJSONObject("data").getInt("notes_hits")+"";
			}catch(Exception e){
				 notes_hits = json.getJSONObject("data").getString("notes_hits");
			}
			
			notes_hits = notes_hits.replace("万+", "0000");
			long total = Long.valueOf(notes_hits);
			dao.update(TKeywordTask.class, Chain.make("status", 2).add("total", total), Cnd.where("id", "=", task.getId()));
			long count = (total-1)/20+1;
			if(count > 50){
				count = 50L;
			}
			TKeywordNextTask knt;
			for (int i = 1; i <= count; i++) {
				knt = new TKeywordNextTask();
				knt.setCreate_time(new Date());
				knt.setKeyword(task.getKeyword());
				knt.setPage_index(i);
				knt.setStatus(0);
				knt.setDefault_status(0);
				knt.setPopu_status(0);
				try {
					dao.fastInsert(knt);
				} catch (Exception e) {
					dao.update(TKeywordNextTask.class,Chain.make("status", 0).add("update_time", new Date()),Cnd.where("keyword", "=",task.getKeyword()).and("page_index", "=",i));
					//e.printStackTrace();
					//logger.error("插入TKeywordNextTask失败.", e);
				}
			}
			logger.info("处理成功:"+url);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.error("处理TKeywordTask任务失败.", e);
			dao.update(TKeywordTask.class, Chain.make("status", 3), Cnd.where("id", "=", task.getId()));
		}

	}

}
